package com.yc.web.Controller;

import com.yc.config.AiConfig;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import dev.langchain4j.service.TokenStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;

import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/ai")
class ChatModelController {

    @Autowired
    ChatModel chatModel;

    @Autowired
    public StreamingChatModel streamingChatModel;

    @Autowired
    public AiConfig.AiAssistant assitant;
//    public AiConfig.Assitant assitant;

    @GetMapping("/chat")
    public String model(@RequestParam(value = "question" ,defaultValue = "你是谁？") String question) {
        String answer = chatModel.chat(question);
        return answer;
    }
    @GetMapping("/streamingchat")
    public void streamingChat(@RequestParam(value = "question") String question) {
        streamingChatModel.chat(question, new StreamingChatResponseHandler() {
            @Override
            public void onPartialResponse(String partialResponse) {
                System.out.print(partialResponse);

            }

            @Override
            public void onCompleteResponse(ChatResponse completeResponse) {
                System.out.println(completeResponse.toString());

            }

            @Override
            public void onError(Throwable error) {
                System.err.println(error.getMessage());

            }
        });
    }

    @GetMapping(value = "/streamingchat2",produces = MediaType.TEXT_PLAIN_VALUE)
    public Flux<String> streamingChat2(@RequestParam(value = "question") String question) {
        Flux<String> flux = Flux.create(fluxSink->{
            streamingChatModel.chat(question, new StreamingChatResponseHandler() {
                @Override
                public void onPartialResponse(String partialResponse) {
                    System.out.print(partialResponse);
                    // 假设原始数据是 ISO-8859-1 编码（常见乱码原因）
                    //String decoded = new String(partialResponse.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                    fluxSink.next(partialResponse); // 直接发送纯文本
                }

                @Override
                public void onCompleteResponse(ChatResponse completeResponse) {
                    fluxSink.complete();
                }

                @Override
                public void onError(Throwable error) {
                    fluxSink.error(error);
                }
            });
        });
        return flux;
    }

    @GetMapping("/assistantchat")
    public String assistantchat(@RequestParam("memoryId") int memoryId,@RequestParam(value = "question") String question) {
        String answer =assitant.chat(memoryId,question);
        return answer;
    }

    @GetMapping(value = "/assistantstreamingchat",produces = MediaType.TEXT_PLAIN_VALUE)
    public Flux<String> assistantstreamingchat(@RequestParam("memoryId") int memoryId,@RequestParam(value = "question") String question) {
        TokenStream tokenStream = assitant.chatStream(memoryId,question);
        return Flux.create(fluxSink -> {
            tokenStream.onPartialResponse(response -> {
                fluxSink.next(response);
            }).onCompleteResponse(response -> {
                fluxSink.complete();
            }).onError(error -> {
                fluxSink.error(error);
            }).start();
        }, FluxSink.OverflowStrategy.BUFFER);  //确保多线程安全的机制

        //低级的写法
//        Flux<String> flux = Flux.create(fluxSink->{
//            streamingChatModel.chat(question, new StreamingChatResponseHandler() {
//                @Override
//                public void onPartialResponse(String partialResponse) {
//                    System.out.print(partialResponse);
//                    // 假设原始数据是 ISO-8859-1 编码（常见乱码原因）
//                    //String decoded = new String(partialResponse.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
//                    fluxSink.next(partialResponse); // 直接发送纯文本
//                }
//
//                @Override
//                public void onCompleteResponse(ChatResponse completeResponse) {
//                    fluxSink.complete();
//                }
//
//                @Override
//                public void onError(Throwable error) {
//                    fluxSink.error(error);
//                }
//            });
//        });
//        return flux;
    }
}
